package main

import (
	"container/list"
	"fmt"
	"math"
	"reflect"
)

/*
2个逆序的链表，要求从低位开始相加，得出结果也逆序输出，返回值是逆序结果链表的头结点。Example:
	Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
	Output: 7 -> 0 -> 8
	Explanation: 342 + 465 = 807
*/
func main() {

	l := list.List{}
	l.PushBack(2)
	l.PushBack(4)
	l.PushBack(3)
	l2 := list.List{}
	l2.PushBack(5)
	l2.PushBack(6)
	l2.PushBack(4)

	numbers := addTwoNumbers(l, l2)
	fmt.Printf("Explanation: %d", numbers)
	fmt.Print("\nOutput: ")
	for {
		if numbers == 0 {
			break
		}
		fmt.Printf("%d -> ", numbers%10)
		numbers = numbers / 10
	}
}

func addTwoNumbers(l1 list.List, l2 list.List) int64 {

	var sum int64 = 0
	// 顺序遍历l1, l2。并求得需要的Explanation值
	i1 := 0
	for front := l1.Front(); front != nil; front = front.Next() {
		i2 := reflect.ValueOf(front.Value).Int()
		// 10的(i1 -1)次方的值求和
		sum += i2 * int64(math.Pow10(i1))
		i1++
	}
	// 同上
	i2 := 0
	for front := l2.Front(); front != nil; front = front.Next() {
		i := reflect.ValueOf(front.Value).Int()
		sum += i * int64(math.Pow10(i2))
		i2++
	}

	return sum
}
